import time
import json

from .user import User,AllUsers
from app.log import logger


class Listen:
    def __init__(self, ws, userAgent):
        self.ws = ws

        if AllUsers.get(userAgent):
            self.user = AllUsers[userAgent]
            self.user.ws = self
        else:
            self.user = User(self, userAgent)
            AllUsers[userAgent] = self.user

        self.start()

    def start(self):
        while not self.ws.closed:
            message = self.ws.receive()  # 接收到消息event.data
            if message is not None:
                self.receive(message)
        self.ws.close()

    # 发送
    def send(self, func, kwargs):
        if not self.ws.closed:
            t = int(time.time() * 1000)
            dt = {
                "func": func,
                "kwargs": kwargs,
                "time": t
            }
            self.ws.send(json.dumps(dt))
        else:
            logger.info(f"failSend(主机掉线):{func}-{kwargs}")

    # 接收
    def receive(self, text):
        try:
            kwargs = json.loads(text)
            func = kwargs.get('func')
            # if (func and self.user.__getattribute__(func)):
            eval(f"self.user.{func}(**kwargs)")
        except Exception as err:
            logger.error(err, exc_info=True)
